
<template>
  <a-card :bordered="false" :bodyStyle="{ height: '100%', padding: '16px', position: 'relative' }">
    <a-spin :spinning="loading">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="直播名称:">
                <a-input
                  v-model="keywords"
                  placeholder="搜索直播名称(回车搜索)"
                  style="width: 80%"
                  @pressEnter="$refs.table.refresh(true)"
                >
                  <a-tooltip slot="suffix" title="搜索直播名称">
                    <a-icon type="search" style="color: rgba(0, 0, 0, 0.45)" @click="$refs.table.refresh(true)" />
                  </a-tooltip>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="上课日期">
                <a-range-picker @change="onChange1" style="width: 80%" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="上课老师:">
                <a-select v-model="queryParam.teacher_id" placeholder="请选择" allowClear style="width: 80%">
                  <a-select-option v-for="(item, index) in teacherList" :key="index" :value="item.id">{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="showSearch">
              <a-col :md="8" :sm="24">
                <a-form-item label="上课状态">
                  <a-select placeholder="请选择" allowClear style="width: 80%" v-model="queryParam.status">
                    <a-select-option :value="1">待开课</a-select-option>
                    <a-select-option :value="2">上课中</a-select-option>
                    <a-select-option :value="3">已完成</a-select-option>
                    <a-select-option :value="99">未成功开课</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
          </a-row>
        </a-form>
      </div>
      <a style="cursor: pointer" v-if="showSearch" @click="showSearch = !showSearch" id="moreButton">
        收起
        <a-icon type="up"></a-icon>
      </a>
      <a style="cursor: pointer" v-if="!showSearch" @click="showSearch = !showSearch" id="moreButton">
        展开
        <a-icon type="down"></a-icon>
      </a>
      <div class="table-operator">
        <a-button type="primary" @click="$router.push({ name: 'createLives' })">新建直播课</a-button>
      </div>
      <s-table
        ref="table"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        class="user_management_table"
        style="margin-top: 20px"
      >
        <span slot="time" slot-scope="text, record">
          {{ record.class_date }}
          <span style="margin-left: 10px">{{ record.start_time }}~{{ record.end_time }}</span>
        </span>
        <span slot="status" slot-scope="text, record">
          <span v-if="record.status == 1">
            <span> <a-badge status="processing" />待上课 </span>
            <span style="margin-left: 10px">
              <a-button size="small" style="font-size: 10px" @click="changeStatus(2, record.id)">开始上课</a-button>
            </span>
          </span>
          <span v-else-if="record.status == 2">
            <span> <a-badge status="warning" />上课中 </span>
            <span style="margin-left: 10px">
              <a-button size="small" style="font-size: 10px" @click="changeStatus(3, record.id)">完成上课</a-button>
            </span>
          </span>
          <span v-else-if="record.status == 3">
            <span> <a-badge status="success" />已完成 </span>
          </span>
          <span v-else-if="record.status == 99">
            <span> <a-badge status="error" />未成功开课 </span>
          </span>
          <span v-else>-</span>
        </span>
        <span slot="student_count" slot-scope="text, record">
          <span v-if="text">
            <a @click="getStudent(record)">{{ text }}</a>
          </span>
          <span v-else>
            {{ text }}
          </span>
        </span>
        <span slot="action" slot-scope="text, record">
          <span v-if="record.status && record.status == 3">
            <!-- 已完成 -->
            <a @click="replay(record)">查看回放</a>
            <a-divider type="vertical" />
            <a @click="getStudent(record)">学员名单</a>
            <a-divider type="vertical" />
            <a @click="del(record)">删除</a>
          </span>
          <span v-else-if="record.status && record.status == 2">
            <!-- 上课中 -->
            <a @click="showActionLive(record)">去直播间</a>
            <a-divider type="vertical" />
            <a v-if="record.status && record.status !== 3" @click="getStudent(record)">学员名单</a>
            <!-- <a-divider type="vertical" />
            <a @click="$router.push({name:'editLives',query:{id:record.id}})">编辑</a> -->
            <a-divider type="vertical" />
            <a v-if="record.status && record.status !== 3" @click="sendNotice(record)">发送通知</a>
          </span>
          <span v-else-if="record.status && record.status == 1">
            <!-- 待上课 -->
            <a v-if="record.status && record.status !== 3" @click="getStudent(record)">学员名单</a>
            <a-divider type="vertical" />
            <a v-if="record.status && record.status !== 3" @click="sendNotice(record)">发送通知</a>
            <a-divider type="vertical" />
            <a @click="$router.push({ name: 'editLives', query: { id: record.id } })">编辑</a>
            <a-divider type="vertical" />
            <a @click="del(record)">删除</a>
          </span>
          <span v-else-if="record.status == 99">
            <a @click="getStudent(record)">学员名单</a>
            <a-divider type="vertical" />
            <a @click="del(record)">删除</a>
          </span>
          <span v-else>-</span>
        </span>
      </s-table>
      <student-modal ref="studentModal"></student-modal>
      <a-modal title="开始直播" :footer="null" :visible="actionLiveVisible" @cancel="actionLiveVisible = false">
        <div class="downloadLiveApp">
          <div class="left">
            <div class="icon">
              <img src="@/assets/unDownload.png" alt="" />
            </div>
            <div class="text">
              <div style="color: #666">没有安装直播客户端</div>
              <div style="color: #999">首次上课需要下载云直播客户端,请先下载并安装</div>
            </div>
          </div>
          <div class="right">
            <a-button @click="download()" type="primary">立即下载</a-button>
          </div>
        </div>
        <div class="downloadLiveApp">
          <div class="left">
            <div class="icon">
              <img src="@/assets/download.png" alt="" />
            </div>
            <div class="text">
              <div style="color: #666">已安装直播客户端</div>
              <div style="color: #999">已安装云直播客户端,请直接启动上课</div>
            </div>
          </div>
          <div class="right">
            <a-button @click="goLive(temporaryData)" type="primary">开始直播</a-button>
          </div>
        </div>
      </a-modal>
      <a-modal
        title="直播回放"
        :footer="null"
        :centered="true"
        :width="1080"
        @cancel="replayVisible = false"
        :visible="replayVisible"
      >
        <iframe :src="iframeUrl" height="700" width="100%" frameborder="0"></iframe>
      </a-modal>
    </a-spin>
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { livesList, delLives, replay, openLiveRoom, sendNotice, changeStatus } from '@/api/lives'
import { teacherList } from '@/api/teacher'
import studentModal from './studentModal'
export default {
  name: 'courseList',
  components: {
    STable,
    Ellipsis,
    studentModal,
  },
  data() {
    return {
      loading: false,
      showSearch: false,
      teacherList: [],
      // 表头
      columns: [
        {
          title: '直播名称',
          dataIndex: 'name',
          fixed: 'left',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '直播模式',
          dataIndex: 'type',
          customRender(text) {
            return text == 1 ? '大班直播' : text == 2 ? '大班互动' : text == 3 ? '小班直播' : '-'
          },
        },
        {
          title: '上课时间',
          dataIndex: 'time',
          width: 200,
          scopedSlots: { customRender: 'time' },
        },
        {
          title: '上课老师',
          dataIndex: 'teacher',
          customRender(text) {
            if (text) {
              return text.name
            } else {
              return '-'
            }
          },
        },
        {
          title: '学员人数',
          align: 'center',
          dataIndex: 'student_count',
          scopedSlots: { customRender: 'student_count' },
        },
        {
          title: '上课状态',
          width: 200,
          dataIndex: 'status',
          ellipsis: true,
          scopedSlots: { customRender: 'status' },
          // customRender(text) {
          //   if (text) {
          //     return text == 1 ? '待上课' : text == 2 ? '上课中' : text == 3 ? '已完成' : ''
          //   } else {
          //     return '-'
          //   }
          // },
        },
        {
          title: '操作',
          width: '420px',
          dataIndex: 'action',
          align: 'right',
          ellipsis: true,
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let postData = {}
        for (let key in this.queryParam) {
          if (this.queryParam[key]) {
            let nature = key
            postData[nature] = this.queryParam[key]
          }
        }
        return livesList(Object.assign(parameter, this.queryParam, { keywords: this.keywords || undefined })).then(
          (res) => {
            return res
          }
        )
      },
      keywords: undefined,
      queryParam: {
        school_id: this.$store.state.user.school,
      },
      temporaryData: null,
      actionLiveVisible: false,
      iframeUrl: '',
      replayVisible: false,
    }
  },
  created() {
    teacherList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
      this.teacherList = res.data
    })
  },
  methods: {
    //更改直播状态
    changeStatus(type, id) {
      let that = this
      this.$confirm({
        title: '提示',
        content: type == 2 ? '确定开始上课？' : type == 3 ? '确定完成上课？' : '',
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          that.loading = true
          changeStatus({ status: type }, id)
            .then((res) => {
              that.$message.success('更改状态成功')
              that.$nextTick(() => {
                that.$refs.table.refresh()
              })
            })
            .catch((err) => {
              if (err.data.message) {
                that.$message.error(err.data.message)
              } else {
                that.$message.error('更改状态失败')
              }
            })
            .finally(() => {
              that.loading = false
            })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    //查看学员
    getStudent(data) {
      if (data && data.id) {
        this.$nextTick(() => {
          this.$refs.studentModal.showModal(data.id, data.status)
        })
      }
    },
    onChange1(date, dateString) {
      this.queryParam.start_date = dateString[0]
      this.queryParam.end_date = dateString[1]
      this.$refs.table.refresh()
    },
    del(data) {
      if (data) {
        let that = this
        this.$confirm({
          title: '提示',
          content: '确定删除?',
          okText: '确定',
          okType: 'primary',
          cancelText: '取消',
          onOk() {
            that.loading = true
            delLives(data.id)
              .then((res) => {
                that.$message.success('删除成功')
                that.$nextTick(() => {
                  that.$refs.table.refresh()
                })
              })
              .catch((err) => {
                if (err.data.message) {
                  that.$message.error(err.data.message)
                } else {
                  that.$message.error('删除失败')
                }
              })
              .finally(() => {
                that.loading = false
              })
          },
          onCancel() {
            console.log('Cancel')
          },
        })
      }
    },
    //回放
    replay(data) {
      if (data) {
        this.loading = true
        replay(data.id)
          .then((res) => {
            if (res.data && res.data.playbackOutUrl) {
              this.iframeUrl = res.data.playbackOutUrl
              this.replayVisible = true
            }
          })
          .catch((err) => {
            if (err.data.message) {
              this.$message.error(err.data.message)
            } else {
              this.$message.error('获取回放资源失败')
            }
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    //去直播间>1.展示开始直播弹窗
    showActionLive(data) {
      if (data && data.id) {
        this.temporaryData = data
        this.actionLiveVisible = true
      }
    },
    //去直播间>2.开始直播
    goLive(data) {
      if (data && data.id) {
        this.loading = true
        openLiveRoom(data.id)
          .then((res) => {
            if (res.launchProtocol) {
              window.open(res.launchProtocol, '_blank')
            }
          })
          .catch((err) => {
            if (err.data.message) {
              this.$message.error(err.data.message)
            } else {
              this.$message.error('打开直播失败')
            }
          })
          .finally(() => {
            this.loading = false
            this.actionLiveVisible = false
          })
      }
    },
    //群发通知
    sendNotice(data) {
      if (data && data.id) {
        let that = this
        this.$confirm({
          title: '你确定要群发微信推送吗?',
          content: '确认后，将自动为本次课的学员发送微信上课提醒消息',
          okText: '确认',
          okType: 'primary',
          cancelText: '取消',
          onOk() {
            that.loading = true
            sendNotice(data.id)
              .then((res) => {
                that.$message.success('发送成功')
              })
              .catch((err) => {
                if (err.data.message) {
                  that.$message.error(err.data.message)
                } else {
                  that.$message.error('发送失败')
                }
              })
              .finally(() => {
                that.loading = false
              })
          },
          onCancel() {
            console.log('Cancel')
          },
        })
      }
    },
    // 下载直播客户端
    download() {
      let type = this.OSnow()
      if (type == 'win') {
        window.open('https://t.talk-fun.com/liveWin', '_blank')
      } else if (type == 'mac') {
        window.open('https://t.talk-fun.com/liveMac', '_blank')
      }
    },
    //判断电脑系统
    OSnow() {
      var agent = navigator.userAgent.toLowerCase()
      var isMac = /macintosh|mac os x/i.test(navigator.userAgent)
      if (agent.indexOf('win32') >= 0 || agent.indexOf('wow32') >= 0) {
        return 'win'
      }
      if (agent.indexOf('win64') >= 0 || agent.indexOf('wow64') >= 0) {
        return 'win'
      }
      if (isMac) {
        return 'mac'
      }
    },
  },
  watch: {
    queryParam: {
      handler(val) {
        this.$refs.table.refresh()
      },
      deep: true,
    },
  },
}
</script>
<style lang="less" scoped>
#moreButton {
  position: absolute;
  top: 8px;
  right: 20px;
}
.downloadLiveApp {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
  .left {
    display: flex;
    width: 350px;
    align-items: center;
    .icon {
      width: 70px;
      height: 70px;
      margin-right: 20px;
      overflow: hidden;
      img {
        width: 100%;
        height: auto;
        overflow: hidden;
      }
    }
    .text {
      width: 255px;
    }
  }
}
</style>
